import {messages, deepFullCopy} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, message } from 'antd'
import AddTable from './add-table-cell'
import requestService from 'containers/request/request.service'

class GiftRequestDetailA extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
        data: [],
        loading: true,
        editingKey: '',
        columns: [
            {
              title: messages('request.key772'/*礼品*/),
              dataIndex: 'formType',
              width: '7%',
              editable: false,
              defaultValue: messages('request.key773'/*礼品申请*/)
            },
            {
              title: messages('request.key774'/*礼品类型*/),
              dataIndex: 'type',
              width: 80,
              editable: false,
              defaultValue: messages('request.key775'/*商务礼品*/)
            },
            {
              title: <div className="red-with-star">{messages('request.key776'/*礼品名称*/)}</div>,
              dataIndex: 'name',
              width: '15%',
              editable: true,
              isRequired: true,
              inputType: 'input',
              trueTitle: messages('request.key776'/*礼品名称*/)
            },
            {
              title: <div className="red-with-star">{messages('request.key777'/*数量*/)}</div>,
              dataIndex: 'applyQuantity',
              width: '15%',
              editable: true,
              isRequired: true,
              inputType: 'inputNumber',
              trueTitle: messages('request.key777'/*数量*/)
            },
            {
              title: <div className="red-with-star">{messages('request.key778'/*金额*/)}</div>,
              dataIndex: 'amount',
              width: '15%',
              editable: true,
              isRequired: true,
              inputType: 'inputNumber',
              trueTitle: messages('request.key778'/*金额*/)
            }],
      info: {},
      dataA: []
    }
  }

  componentWillReceiveProps (nextProps) {
    if (this.state.info !== nextProps.info && this.props.totalAmount !== nextProps.totalAmount) {
      this.getTableList()
    }
    this.setState({
      info: nextProps.info
    })
  }

  componentDidMount () {
    this.props.onRef(this)
    this.setState({
      info: this.props.info
    })
    this.getTableList()
  }

  // 获取当前表格的列表数据
  getTableList () {
    const {id, type} = this.props;
    this.setState({
      loading: true
    }, () => {
      requestService.getGiftRequestDetail(id, 1).then(res => {
        let data = deepFullCopy(res.data)
        const newData = data.map((item, index) => {
          item.key = index + 1
          item.formType = messages('request.key773'/*礼品申请*/)
          return item
        })
        this.setState({
          data: newData,
          loading: false,
          dataA: res.data
        })
        if (type) {
          this.props.isCallBack({
            giftA: res.data,
            code: 'giftA'
          })
        }
      })
    })
  }

  // 增加
  handleOnAdd = () => {
    this.child.handleAdd()
  }

  // 删除
  onDelete = (record) => {
    const { data, dataA } = this.state
    if (record.id) {
      requestService.giftRequestDetailTableDelete(record.id).then(res => {
        if (res.data) {
          this.setState({
            data: data.filter(item => item.key !== record.key),
            dataA: dataA.filter(item => item.id !== record.id)
          },() => {
            message.success(messages('request.key780'/*删除成功*/))
            this.props.isCallBack(true)
          })
        }
      })
    } else {
      this.setState({ data: data.filter(item => item.key !== record.key) },() => {
        message.success(messages('request.key780'/*删除成功*/))
      })
    }
  }

  // 子组件修改父组件的数据
  onChange = (value) => {
    this.setState({
      data: value
    })
  }

  // 保存
  onSave = (value) => {
    this.setState({loading: true})
    const { record, index, row } = value
    let json = {
      ...record,
      ...row
    }

    json.employeeName = (row.employeeName && row.employeeName[0].fullName) ? row.employeeName[0].fullName : json.employeeName
    json.employeeId = (row.employeeName && row.employeeName[0].employeeID) ? row.employeeName[0].employeeID: json.employeeId

    // let needRepeat = false;
    json.formType = 1
    // this.state.data && this.state.data.map((item, indexB) => {
    //   if (index !== indexB) {
    //     if (item.type === json.type) {
    //       needRepeat = true;
    //     }
    //   }
    // })
    // if (needRepeat) {
    //   message.warning("该礼品已添加")
    //   this.setState({loading: false})
    //   return
    // }
    if (record.id) {// 编辑的保存
      requestService.giftRequestDetailTableEdit(json).then(res => {
        let data = deepFullCopy(res.data)
        data.formType = messages('request.key773'/*礼品申请*/)
        this.onSaveFunc(record, index, data, res.data )
        message.success(messages('request.key779'/*保存成功*/))
      }).catch(() => {
        this.setState({loading: false})
      })
    } else { // 新增的保存
      const {formOID, id} = this.props;
      json.formOid = formOID
      json.applicationId = id
      requestService.giftRequestDetailTableAdd(json).then(res => {
        let data = deepFullCopy(res.data)
        data.formType = messages('request.key773'/*礼品申请*/)
        this.onSaveFunc(record, index, data, res.data )
        message.success(messages('request.key779'/*保存成功*/))
      }).catch(() => {
        this.setState({loading: false})
      })
    }
  }

  // 保存之后的回调
  onSaveFunc(record, index, row, data ) {
    const newData = [...this.state.data];
    const newDataA = [...this.state.dataA];
    row.key = new Date().getTime();
    newData.splice(index, 1, {
      ...record,
      ...row,
    })
    newDataA.splice(index, 1, data)
    this.setState({
      data: newData,
      loading: false,
      dataA: newDataA
    })
    this.child.cancel()
    this.props.onChangeEdit(false);
    this.props.isCallBack(true)
  }

  render() {
    const { data, loading, columns, info } = this.state
    const { isDoneApproved } = this.props;
    const isEdit = ['10011000', '10011001', '10011002'].includes(`${info.status}${info.rejectType}`) && info.formCode === 'SQ002' ? isDoneApproved && isDoneApproved === 'true' ? false : true : false
    return (
      <div className="request-info">
        <div className="tab-container">
            <h3 className="sub-header-title">
              {messages('request.key762'/*申请单行信息*/)}
              {
                isEdit && (<span className="sub-header-title-edit" onClick={this.handleOnAdd}>{messages('request.key763'/*+新增*/)}</span>)
              }
            </h3>
            <AddTable
              onRef={ref => this.child = ref}
              loading={loading}
              isEdit={isEdit}
              value={data}
              operationKey={"addTableA"}
              columns={columns}
              onDelete={this.onDelete}
              onChange={this.onChange}
              onSave={this.onSave}
              editLines={this.props.editLines}
              onChangeEdit={this.props.onChangeEdit}
              info={info}
              title={() => (<div className="sub-header-giftRequestDetail-title">{messages('request.key781'/*A礼品申请*/)}</div>)}/>
        </div>
      </div>
    )
  }
}

GiftRequestDetailA.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return { }
}

const wrappedGiftRequestDetailA = Form.create()(GiftRequestDetailA);

export default connect(mapStateToProps)(wrappedGiftRequestDetailA)
